package com.island.controller.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.island.mapper.user.UserMapper;
import com.island.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/verifyPwd")
    @ResponseBody
    public String verifyPwd(String oldpassword, HttpServletRequest req){    //与前端交互，验证用户修改密码的时候的旧密码输入是否正确
        User user = (User) req.getSession().getAttribute("userSession");
        //使用Map集合存储返回给前端的数据
        Map<String,String> resultMap = new HashMap<String, String>();

        if (user==null){//session中的user对象失效了
            resultMap.put("flag","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("flag","error");
        }else {
            if (oldpassword.equals(user.getUserPassword())){//输入的密码匹配
                resultMap.put("flag","true");
            }else {//输入的密码不匹配
                resultMap.put("flag","false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }
    @RequestMapping("/updatePwd")
    public String updatePwd(String oldpassword, String newpassword, String rnewpassword, HttpServletRequest req){   //修改密码的controller，调用service层
        User userSession = (User) req.getSession().getAttribute("userSession");
        if (userSession.getUserPassword().equals(oldpassword)){
            int i = userMapper.updatePwd(newpassword, userSession.getId());
            if (i>0){
                req.setAttribute("message","密码修改成功！请使用新密码重新登陆");
                //移除用户的session，利用过滤器阻止用户再进行操作,直接跳转error.jsp页面
                req.getSession().removeAttribute("userSession");
            } else {
                req.setAttribute("message","密码修改失败");
            }
        } else {
            req.setAttribute("message","密码设置有误，请重新输入！");
        }
        return "pwdmodify";
    }

    @RequestMapping("/test01")
    public String test01(Model model){
        model.addAttribute("msg","Hello thymeleaf");
        return "adduser";
    }
}
